<template>
  <el-dialog
    v-model="visible"
    title="任务数据详情"
    width="900px"
    :before-close="handleClose"
    class="unified-dialog task-data-detail-dialog"
    :close-on-click-modal="false"
    append-to-body
  >
    <template #header>
      <div class="dialog-header">
        <div class="header-icon header-icon-primary">
          <el-icon><View /></el-icon>
        </div>
        <div class="header-content">
          <h3>任务数据详情</h3>
          <p>查看任务数据的详细信息</p>
        </div>
      </div>
    </template>

    <div v-if="taskData" class="dialog-content">
      <el-descriptions :column="2" border size="default">
        <!-- 基本信息 -->
        <el-descriptions-item label="ID" label-class-name="detail-label">
          {{ taskData.id }}
        </el-descriptions-item>
        <el-descriptions-item label="配置ID" label-class-name="detail-label">
          {{ taskData.config_id }}
        </el-descriptions-item>

        <el-descriptions-item label="Redis Key" :span="2" label-class-name="detail-label">
          <div class="detail-text">{{ taskData.redis_key }}</div>
        </el-descriptions-item>

        <el-descriptions-item label="Key前缀" label-class-name="detail-label">
          {{ taskData.key_prefix }}
        </el-descriptions-item>
        <el-descriptions-item label="数据类型" label-class-name="detail-label">
          <el-tag :type="getDataTypeTag(taskData.data_type)" size="small">
            {{ taskData.data_type || 'string' }}
          </el-tag>
        </el-descriptions-item>

        <!-- 业务信息 -->
        <el-descriptions-item label="任务ID" label-class-name="detail-label">
          <span v-if="taskData.task_id">{{ taskData.task_id }}</span>
          <span v-else class="text-muted">-</span>
        </el-descriptions-item>
        <el-descriptions-item label="任务类型" label-class-name="detail-label">
          <span v-if="taskData.task_type">{{ taskData.task_type }}</span>
          <span v-else class="text-muted">-</span>
        </el-descriptions-item>

        <el-descriptions-item label="用户ID" :span="2" label-class-name="detail-label">
          <span v-if="taskData.user_id">{{ taskData.user_id }}</span>
          <span v-else class="text-muted">-</span>
        </el-descriptions-item>

        <!-- Redis数据信息 -->
        <el-descriptions-item label="TTL" label-class-name="detail-label">
          {{ formatTTL(taskData.ttl) }}
        </el-descriptions-item>
        <el-descriptions-item label="数据大小" label-class-name="detail-label">
          {{ formatBytes(taskData.data_size) }}
        </el-descriptions-item>

        <el-descriptions-item label="过期时间" label-class-name="detail-label">
          <span v-if="taskData.expire_time">{{ taskData.expire_time }}</span>
          <span v-else class="text-muted">-</span>
        </el-descriptions-item>
        <el-descriptions-item label="删除状态" label-class-name="detail-label">
          <el-tag :type="getDeletionStatusTag(taskData.deletion_status)" size="small">
            {{ getDeletionStatusText(taskData.deletion_status) }}
          </el-tag>
        </el-descriptions-item>

        <el-descriptions-item label="最后看到时间" label-class-name="detail-label">
          <span v-if="taskData.last_seen_time">{{ taskData.last_seen_time }}</span>
          <span v-else class="text-muted">-</span>
        </el-descriptions-item>
        <el-descriptions-item label="采集时间" label-class-name="detail-label">
          {{ taskData.collection_time }}
        </el-descriptions-item>

        <!-- 任务数据（JSON） -->
        <el-descriptions-item label="任务数据" :span="2" label-class-name="detail-label">
          <div class="detail-json">
            <el-button 
              v-if="taskData.task_data"
              size="small" 
              text 
              type="primary"
              @click="copyToClipboard(getRawJsonValue(taskData.task_data), '任务数据')"
              :icon="DocumentCopy"
              style="float: right;"
            >
              复制
            </el-button>
            <pre v-if="taskData.task_data" class="json-content">
              {{ formatJsonString(taskData.task_data) }}
            </pre>
            <span v-else class="text-muted">-</span>
          </div>
        </el-descriptions-item>

        <!-- 时间信息 -->
        <el-descriptions-item label="创建时间" label-class-name="detail-label">
          {{ taskData.created_at }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间" label-class-name="detail-label">
          {{ taskData.updated_at }}
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed } from 'vue'
import { ElMessage } from 'element-plus'
import { View, DocumentCopy } from '@element-plus/icons-vue'
import { copyToClipboard as copyTextUtil } from '@/utils/clipboard'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  taskData: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue'])

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 获取删除状态标签
const getDeletionStatusTag = (status) => {
  const statusMap = {
    active: 'success',
    normal_expire: 'info',
    early_deleted: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取删除状态文本
const getDeletionStatusText = (status) => {
  const statusMap = {
    active: '活跃',
    normal_expire: '正常过期',
    early_deleted: '提前删除'
  }
  return statusMap[status] || status
}

// 获取数据类型标签
const getDataTypeTag = (type) => {
  const typeMap = {
    string: 'primary',
    hash: 'success',
    list: 'warning',
    set: 'info',
    zset: 'danger'
  }
  return typeMap[type] || 'info'
}

// 格式化TTL
const formatTTL = (ttl) => {
  if (ttl === null || ttl === undefined) return '-'
  if (ttl === -1) return '永不过期'
  if (ttl === -2) return '不存在'
  if (ttl < 60) return `${ttl}秒`
  if (ttl < 3600) return `${Math.floor(ttl / 60)}分钟`
  if (ttl < 86400) return `${Math.floor(ttl / 3600)}小时`
  return `${Math.floor(ttl / 86400)}天`
}

// 格式化字节
const formatBytes = (bytes) => {
  if (bytes === null || bytes === undefined || bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

// 格式化JSON字符串（用于显示）
const formatJsonString = (value, indent = 2) => {
  if (!value) return '-'
  
  try {
    // 如果是字符串，尝试解析为JSON对象再格式化
    if (typeof value === 'string') {
      try {
        const parsed = JSON.parse(value)
        return JSON.stringify(parsed, null, indent)
      } catch (e) {
        // 如果不是有效的JSON字符串，直接返回
        return value
      }
    }
    
    // 如果是对象，转成格式化的字符串
    return JSON.stringify(value, null, indent)
  } catch (error) {
    // 如果所有尝试都失败，返回原始值
    return typeof value === 'string' ? value : String(value)
  }
}

// 获取原始 JSON 值（用于复制）
const getRawJsonValue = (value) => {
  if (!value) return ''
  
  try {
    // 如果是字符串，直接返回
    if (typeof value === 'string') {
      return value
    }
    
    // 如果是对象，转成格式化的字符串
    return JSON.stringify(value, null, 2)
  } catch (error) {
    return typeof value === 'string' ? value : String(value)
  }
}

// 复制到剪贴板
const copyToClipboard = async (text, label = '') => {
  try {
    await copyTextUtil(text, label)
    ElMessage.success(label ? `${label}已复制到剪贴板` : '已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.task-data-detail-dialog :deep(.el-dialog__header) {
  padding: 0;
}

.task-data-detail-dialog :deep(.el-dialog__body) {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
}

.header-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.header-icon-primary {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
}

.header-content h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-content p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.dialog-content {
  margin-top: 20px;
}

.detail-label {
  font-weight: 600;
  color: #606266;
}

.detail-text {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  color: #303133;
  word-break: break-all;
}

.text-muted {
  color: #909399;
  font-style: italic;
}

.detail-json {
  position: relative;
}

.json-content {
  margin: 8px 0 0 0;
  padding: 12px;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.6;
  color: #303133;
  overflow-x: auto;
  max-height: 400px;
  overflow-y: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}
</style>













